const crypto = require('crypto');
const log4js = require('../config/log4js').log4js
const logger = log4js.getLogger('comm-auth');

var auth = {

	login_user(req, user, remember) {
		if (remember && req.session.cookie) {
			req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 7
		}
		req.session.loginUser = user;
	},

	logout_user(req) {
		if (req.session && req.session.loginUser) {
			logger.info('delete', req.session.loginUser)
			delete req.session.loginUser;
			req.session.destroy()
			return true
		}

		return false
	},

	logout_admin_user(req) {
		if (req.session && req.session.adminLoginUser) {
			logger.info('delete', req.session.adminLoginUser)
			delete req.session.adminLoginUser;
			req.session.destroy()
			return true
		}

		return false
	},

	encryption(data, key) {
		if (key == undefined) {
			key = crypto.createHash('sha256').update("slidego.cn-2019@", 'utf8').digest();
		} else {
			key = crypto.createHash('sha256').update(key, 'utf8').digest();
		}
		var iv = "4329022405963708";
		var clearEncoding = 'utf8';
		var cipherEncoding = 'base64';
		var cipherChunks = [];
		var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
		//cipher.setAutoPadding(true);

		cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
		cipherChunks.push(cipher.final(cipherEncoding));

		return cipherChunks.join('');
	},

	//data 是你的准备解密的字符串,key是你的密钥
	decryption(data, key) {
		var iv = '4329022405963708';
		var clearEncoding = 'utf8';
		var cipherEncoding = 'base64';
		var cipherChunks = [];
		if (key == undefined) {
			key = crypto.createHash('sha256').update("slidego.cn-2019@", 'utf8').digest();
		} else {
			key = crypto.createHash('sha256').update(key, 'utf8').digest();
		}
		var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
		//decipher.setAutoPadding(false);

		cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding));
		cipherChunks.push(decipher.final(clearEncoding));
		return cipherChunks.join('');
	}
}

module.exports = auth